import {Component, OnInit} from '@angular/core';
import {TweetsService} from './tweets.service';
import { NzMessageService } from 'ng-zorro-antd/message';

@Component({
  selector: 'app-tweets',
  templateUrl: './tweets.component.html',
  styleUrls: ['./tweets.component.css']
})
export class TweetsComponent implements OnInit {

  content = '';
  moreData: boolean = false;
  initLoading = true; // bug
  loading: false;
  data: any[] = [];
  list: any[] = [];

  constructor(private tweetsService: TweetsService,
              private messageService: NzMessageService,
  ) {
  }

  ngOnInit(): void {
    this.getData();
  }

  getData(more: boolean = false) {
    let page = this.list.length / 10;
    this.tweetsService.findPage({page, size: 10}).subscribe((res) => {
      if (res.code === 1) {
        this.list = more ? this.list.concat(res.data.content) : res.data.content;
        console.log(this.list);
        this.moreData = res.data.content.length > 9;
      } else {
        this.messageService.error(res.message);
      }
    }, () => {
      this.initLoading = false;
    }, () => {
      this.initLoading = false;
    });
  }

  insertTweets() {
    console.log(this.content);
    this.tweetsService.update({content: this.content}).subscribe((data) => {
      if (data.code === 1) {
        this.content = '';
        this.messageService.success('发布成功');
        // 重新加载
        this.refreshList();
      } else {
        this.messageService.error(data.message);
      }

    }, () => {
    }, () => {
    });
  }

  like(item){
    this.tweetsService.up(item.id).subscribe(res => {
      if (res.code === 1) {
        item.up = item.up? item.up + 1:  1;
      } else {
        this.messageService.error(res.message);
      }
    });

  }

  refreshList() {
    this.list = [];
    this.getData();
  }

}
